(function (exports) {
    var $ = null;

    var TicketShopLayer = cc.Layer.extend({
        TicketAllData: [],
        KucunData: [],
        ticketNum : 0,
        secondToTime: function (second) {
            second = parseInt(second);
            var hour = Math.floor(second / 3600);
            var minite = Math.floor((second - hour * 3600 ) / 60);
            var sec = second - hour * 3600 - minite * 60;

            hour = hour < 10 ? '0' + hour : hour;
            minite = minite < 10 ? '0' + minite : minite;
            sec = sec < 10 ? '0' + sec : sec;
            return hour + ':' + minite + ':' + sec;
        },
        onEnter: function () {
            cc.Layer.prototype.onEnter.call(this);
            var that = this;
            var data2 = { //获取新的礼券数量
                UserID: gameData.uid + "",
                GameID: app.area + "",
                AppID: app.appId + "",
                GoodsKeys: [{GoodsType: 3, GoodsCode: "liquan"}]  //获取所有道具
            };
            network.sendProto(1055, data2);//核对礼券

            var data = {
                userid: gameData.uid + "",
                game_id: app.area + "",
                cache_version: 0  //parseInt(cc.sys.localStorage.getItem('cur_version')) || 0    //获取所有道具
            };
            network.sendProto(1041, data);

            this.addListener(1042, function (data) {
                hideLoading();

                var cur_version = data.cur_version; // 当前配置版本号
                cc.sys.localStorage.setItem('cur_version', cur_version);

                var exchange_list = data.exchange_list; //兑换商品列表 (版本号一致时返回空)
                var stock_info = data.stock_info; //库存余量

                // for (var i = 0; i < exchange_list.length; i++) {
                //     exchange_list[i].sell_type = 3;
                //     var nowTime = new Date().getTime();
                //     exchange_list[i].starttime = nowTime - 5000;
                //     exchange_list[i].endtime = nowTime + 5000;
                // }
                that.TicketAllData = exchange_list;
                that.KucunData = stock_info;

                that.initTicketLayer();

            });

            this.addListener(1044, function (data) {
                hideLoading();
                if(data.errorCode != 0){
                    showAlert(data.errorMsg);
                    return;
                }
                showAlert("兑换成功!");
                $('convert_top').setVisible(false);
                $('convert_address').setVisible(false);
                //刷新礼券商城
                var data = {
                    userid: gameData.uid + "",
                    game_id: app.area + "",
                    cache_version: 0  //parseInt(cc.sys.localStorage.getItem('cur_version')) || 0    //获取所有道具
                };
                network.sendProto(1041, data);

                var data2 = { //获取新的礼券数量
                    UserID: gameData.uid + "",
                    GameID: app.area + "",
                    AppID:app.appId + "",
                    GoodsKeys: [{GoodsType: 3, GoodsCode: "liquan"}]  //获取所有道具
                };
                network.sendProto(1055, data2);//核对礼券
                network.send(3013); //核对金币
            });

            this.addListener(1056, function (data) {
                var GoodsList = data.GoodsList;
                for (var i = 0; i < GoodsList.length; i++) {
                    if (GoodsList[i].Code == "liquan") {
                        var ticketNum = equalNum(GoodsList[i].Quantity);
                        $('lb_ticket_num').setString(ticketNum);
                        that.ticketNum = GoodsList[i].Quantity == undefined ? 0 : GoodsList[i].Quantity;
                        break;
                    }
                }
            });
            that.updateFk = cc.eventManager.addCustomListener('updateFk', function (event) {
                var goldNum = equalNum(gameData.numOfCards[0]);
                that.lb_gold.setString(goldNum);
            });
        },
        addListener: function (code, listener) {
            network.addListener(code, listener, this);
        },
        onExit: function () {
            var that = this;
            cc.Layer.prototype.onExit.call(this);
            if (that.countFunc) {
                that.unschedule(that.countFunc);
                that.countFunc = null;
            }
            cc.eventManager.removeListener(this.updateFk);
            network.removeListenersForTarget(this);
        },
        //根据id获取  库存量
        getResidueById: function (id) {
            var that = this;
            for (var i = 0; i < that.KucunData.length; i++) {
                if (that.KucunData[i].id == id) {
                    return that.KucunData[i].stock;
                }
            }
            return 0;
        },
        ctor: function () {
            this._super();
            var that = this;

            var scene = loadNodeCCS(res.TicketShopLayer_json, this);
            $ = create$(this.getChildByName('Layer'));
            this._$ = $;

            $('tip_no').setVisible(false);
            $('convert_top').setVisible(false);
            $('convert_address').setVisible(false);

            // var size = $('bg').getContentSize();
            // var piaodai = getCreateRoomAni(7);
            // piaodai.setPosition(size.width/2, size.height - 50);
            // $('bg').addChild(piaodai);

            TouchUtil.setOnclickListener($('btn_close'), function (node) {
                that.parent.removeFromParent(true);
            });

            TouchUtil.setOnclickListener($('btn_convert_record'), function (node) {
                that.addChild(new TicketShopRecord());
            });
            var goldNum = equalNum(gameData.numOfCards[0]);
            that.lb_gold = $('lb_gold_num');
            that.lb_gold.setString(goldNum);
            var ticketNum = equalNum(that.ticketNum);
            $('lb_ticket_num').setString(ticketNum);
        },

        initTicketLayer: function () { //idx 0 道具 1 话费 2 门票
            var that = this;
            //筛选 没开始 还有已结束
            var TicketAllData = that.TicketAllData;
            for (var i = 0; i < that.TicketAllData.length; i++) {
                var data = that.TicketAllData[i];
                var sell_type = data.sell_type;//售卖类型 3是限时
                var nowTime = new Date().getTime();
                if (sell_type == 3) { //未开始 或者已结束售卖的 删除
                    if (nowTime < data.starttime || nowTime > data.endtime) {
                        TicketAllData.splice(i, 1);
                    }
                }
            }
            that.TicketAllData = TicketAllData;

            $('tip_no').setVisible(that.TicketAllData.length <= 0);
            if (that.tableview) {
                tableViewRefresh(that.tableview); //刷新一遍 用于查询
            } else {
                var tableviewLayer = $('tableview');
                var tableview = new cc.TableView(that, cc.size(tableviewLayer.getContentSize().width, tableviewLayer.getContentSize().height));
                tableview.setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL);
                tableview.setVerticalFillOrder(cc.TABLEVIEW_FILL_TOPDOWN);
                tableview.setPosition(0, 0);
                tableview.setDelegate(that);
                tableview.setBounceable(true);
                tableviewLayer.addChild(tableview);
                that.tableview = tableview;
            }
        },
        //点击cell
        tableCellTouched: function (table, cell) {
        },
        tableCellSizeForIndex: function (table, idx) {
            return cc.size(940, 230);
        },
        tableCellAtIndex: function (table, idx) {
            var that = this;

            var cell = table.dequeueCell();
            if (cell == null) {
                cell = new cc.TableViewCell();
                // var row0 = ccs.load(res.TicketShop_Item_json, getCCSFileNamePath(res.TicketShop_Item_json)).node;
                var row0 = loadNodeCCSItem(res.TicketShop_Item_json);
                row0.setName('cellrow');
                cell.addChild(row0);
            }
            var Layer = cell.getChildByName('cellrow');

            var node_0 = $('node_0', Layer);
            node_0.setVisible(false);
            for (var i = 0; i < 4; i++) {
                (function (i) {
                    var node = $('node_' + (i + 1), Layer);
                    if (!node) {
                        node = duplicateNode(node_0);
                        node.setPositionX(node_0.getPositionX() + i * 230 + 15);
                        node.setPositionY(node_0.getPositionY());
                        node_0.getParent().addChild(node);
                        node.setName('node_' + (i + 1));
                    }
                    node.setVisible(false);
                    var curIdx = idx * 4 + i;
                    if (that.TicketAllData[curIdx]) {
                        var data = that.TicketAllData[curIdx]; //当前node的信息
                        node.setVisible(true);

                        var num = that.getResidueById(data.id);
                        $('item_name', node).setString(data.name);
                        $('item_num', node).setVisible(num > 0);
                        $('item_num', node).setString('剩余:' + num);

                        downLoadImage(data.url, function (texture) {
                            $('item', node).removeAllChildren();
                            var sp = new cc.Sprite(texture);
                            sp.setScale(0.8);
                            $('item', node).addChild(sp);
                        });
                        // loadUrlImageToSprite(data.url, $('item', node));

                        $('item_time', node).setString(data.price);

                        $('img_discount', node).setVisible(data.sell_type == 1);
                        $('img_new', node).setVisible(data.sell_type == 2);
                        $('img_limit_time', node).setVisible(data.sell_type == 3);

                        $('touch_item', node).setLocalZOrder(100);
                        TouchUtil.setOnclickListener($('touch_item', node), function (sender) {
                            if (!that.tableview.isTouchMoved()){
                                that.showExchangeLayer(data);
                            }
                        }, {"swallowTouches": false});
                    }
                })(i);
            }
            return cell;
        },
        numberOfCellsInTableView: function (table) {
            return Math.ceil(this.TicketAllData.length / 4);
        },
        showExchangeLayer: function (data) {
            var that = this;
            $('convert_address').setVisible(false);
            $('convert_top').setVisible(true); //展示兑换界面
            $('convert_top').setPositionX(640);
            $('convert_top.lb_name').setString(data.name);
            var num = that.getResidueById(data.id);
            $('convert_top.lb_num').setVisible(num > 0);
            $('convert_top.lb_num').setString("剩余:" + num);
            loadUrlImageToSprite(data.url, $('convert_top.item_img'));
            $('convert_top.lb_content').setString(data.desc);
            $('convert_top.count_node.lb_buy_num').setString('1');

            that.TimeCountDown($('convert_top'), data, function () {
                //时间到 按钮智慧  礼券图标置灰
                $('convert_top.lb_limit_time').setString("00:00:00");
                $('convert_top.btn_exchange').setVisible(false);
                $('convert_top.btn_not_buy').setVisible(true);
                // $('convert_top.img_not_buy').setTexture(res.img_not_buy);
                var data = { //刷新礼券商城
                    userid: gameData.uid + "",
                    game_id: app.area + "",
                    cache_version: 0  //parseInt(cc.sys.localStorage.getItem('cur_version')) || 0    //获取所有道具
                };
                network.sendProto(1041, data);
            });

            TouchUtil.setOnclickListener($('convert_top.btn_close'), function (node) {
                $('convert_top').setVisible(false);
                if (that.countFunc) {
                    that.unschedule(that.countFunc);
                    that.countFunc = null;
                }
            });

            var ticketNum = parseInt(that.ticketNum);

            $('convert_top.count_node').setVisible(data.tag_type == 2 || data.tag_type == 4); //道具展示 + -
            $('convert_top.lb_content_0').setVisible(data.tag_type == 1);
            //展示价格
            var needMoney = data.price * parseInt($('convert_top.count_node.lb_buy_num').getString());
            $('convert_top.lb_need_money').setString(needMoney);
            if (ticketNum < needMoney) { //判断需要的券是否足够
                $('convert_top.btn_exchange').setVisible(false);
                $('convert_top.btn_not_buy').setVisible(true);
                // $('convert_top.img_not_buy').setTexture(res.img_not_buy);
            } else {
                $('convert_top.btn_exchange').setVisible(true);
                $('convert_top.btn_not_buy').setVisible(false);
                // $('convert_top.img_not_buy').setTexture(res.img_can_buy);
            }
            TouchUtil.setOnclickListener($('convert_top.count_node.btn_add'), function (node) {
                var buyNum = parseInt($('convert_top.count_node.lb_buy_num').getString());
                if (data.sell_type == 3 && that.time <= 0) { //判断限时商品倒计 是否走完
                    return;
                }
                if (num == 0 || (buyNum <= num && num > 0)) {
                    ++buyNum;
                    $('convert_top.count_node.lb_buy_num').setString(buyNum);
                    var needMoney = data.price * buyNum;
                    $('convert_top.lb_need_money').setString(needMoney);
                    if (ticketNum < needMoney) { //判断需要的券是否足够
                        $('convert_top.btn_exchange').setVisible(false);
                        $('convert_top.btn_not_buy').setVisible(true);
                        // $('convert_top.img_not_buy').setTexture(res.img_not_buy);
                    } else {
                        $('convert_top.btn_exchange').setVisible(true);
                        $('convert_top.btn_not_buy').setVisible(false);
                        // $('convert_top.img_not_buy').setTexture(res.img_can_buy);
                    }
                }
            });
            TouchUtil.setOnclickListener($('convert_top.count_node.btn_jian'), function (node) {
                var buyNum = parseInt($('convert_top.count_node.lb_buy_num').getString());
                if (data.sell_type == 3 && that.time <= 0) { //判断限时商品倒计 是否走完
                    return;
                }
                if (buyNum > 1) {
                    --buyNum;
                    $('convert_top.count_node.lb_buy_num').setString(buyNum);
                    var needMoney = data.price * buyNum;
                    $('convert_top.lb_need_money').setString(needMoney);
                    if (ticketNum < needMoney) { //判断需要的券是否足够
                        $('convert_top.btn_exchange').setVisible(false);
                        $('convert_top.btn_not_buy').setVisible(true);
                        // $('convert_top.img_not_buy').setTexture(res.img_not_buy);
                    } else {
                        $('convert_top.btn_exchange').setVisible(true);
                        $('convert_top.btn_not_buy').setVisible(false);
                        // $('convert_top.img_not_buy').setTexture(res.img_can_buy);
                    }
                }
            });

            TouchUtil.setOnclickListener($('convert_top.btn_exchange'), function (node) {
                var buyNum = parseInt($('convert_top.count_node.lb_buy_num').getString());
                var netdata = {
                    userid: gameData.uid + "",
                    game_id: app.area + "",
                    product_id: data.id + "",
                    count: buyNum
                };

                if (data.tag_type == 3) {
                    that.showAddressLayer(data, buyNum);
                } else {
                    network.sendProto(1043, netdata);
                }
            });
        },


        showAddressLayer: function (data, count) {
            var that = this;
            $('convert_top').setVisible(false);
            $('convert_address').setVisible(true); //展示兑换界面
            $('convert_address').setPositionX(640);
            $('convert_address.lb_name').setString(data.name);
            var num = that.getResidueById(data.id);
            $('convert_address.lb_num').setVisible(num > 0);
            $('convert_address.lb_num').setString("剩余:" + num);
            loadUrlImageToSprite(data.url, $('convert_address.item_img'));

            TouchUtil.setOnclickListener($('convert_address.btn_close'), function (node) {
                $('convert_address').setVisible(false);
                // if (that.countFunc) {
                //     cc.director.getScheduler().unschedule(that.countFunc, that);
                //     that.countFunc = null;
                // }
            });

            $('convert_address.img_time').setVisible(false);
            $('convert_address.lb_limit_time').setVisible(false);
            // that.TimeCountDownCountDown($('convert_address'), data, function () {
            //     $('convert_address.lb_limit_time').setString("00:00:00");
            //     $('convert_address.btn_exchange').setVisible(false);
            // });


            var v_input1 = $('convert_address.input_name');
            v_input1.setTextVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_CENTER);
            v_input1.addEventListener(function (sender, type) {
                switch (type) {
                    case ccui.TextField.EVENT_ATTACH_WITH_IME: //点开输入框
                        break;
                    case ccui.TextField.EVENT_DETACH_WITH_IME://输入完毕
                        $('convert_address').setPositionY(0);
                        break;
                    case ccui.TextField.EVENT_INSERT_TEXT://插入字符
                        break;
                    case ccui.TextField.EVENT_DELETE_BACKWARD://点击enter
                        break;
                    default:
                        break;
                }
            });
            var v_input2 = $('convert_address.input_call');
            v_input2.setTextVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_CENTER);
            v_input2.addEventListener(function (sender, type) {
                switch (type) {
                    case ccui.TextField.EVENT_ATTACH_WITH_IME: //点开输入框
                        break;
                    case ccui.TextField.EVENT_DETACH_WITH_IME://输入完毕
                        $('convert_address').setPositionY(0);
                        break;
                    case ccui.TextField.EVENT_INSERT_TEXT://插入字符
                        break;
                    case ccui.TextField.EVENT_DELETE_BACKWARD://点击enter
                        break;
                    default:
                        break;
                }
            });
            var v_input3 = $('convert_address.input_add');
            v_input3.setTextVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_TOP);
            v_input3.addEventListener(function (sender, type) {
                switch (type) {
                    case ccui.TextField.EVENT_ATTACH_WITH_IME: //点开输入框
                        break;
                    case ccui.TextField.EVENT_DETACH_WITH_IME://输入完毕
                        $('convert_address').setPositionY(0);
                        break;
                    case ccui.TextField.EVENT_INSERT_TEXT://插入字符
                        break;
                    case ccui.TextField.EVENT_DELETE_BACKWARD://点击enter
                        break;
                    default:
                        break;
                }
            });


            TouchUtil.setOnclickListener($('convert_address.btn_exchange'), function (node) {
                var name = v_input1.getString();
                var iphone = v_input2.getString();
                var address = v_input3.getString();

                if (name.length <= 0) {
                    showAlert("请输入收货人姓名!");
                    return;
                }

                var m_AllNum = /^[0-9]\d*$/.test(iphone);
                if (!m_AllNum || iphone.length != 11 || iphone[0] == '0') {
                    showAlert("输入的手机号有误!");
                    return;
                }
                if (address.length <= 0) {
                    showAlert("请输入收货地址!");
                    return;
                }

                var netdata = {
                    userid: gameData.uid + "",
                    game_id: app.area + "",
                    product_id: data.id + "",
                    count: count,
                    receiver: {name: encodeURIComponent(name) , phone: iphone, address: encodeURIComponent(address)}
                };
                network.sendProto(1043, netdata);
            });
        },
        TimeCountDown: function (node, data, callBack) {
            var that = this;

            $('img_time', node).setVisible(data.sell_type == 3);
            $('lb_limit_time', node).setVisible(data.sell_type == 3);

            if (data.sell_type == 3) {
                //时间倒计时
                var curTime = new Date().getTime();
                that.time = Math.floor(( parseInt(data.endtime) - curTime) / 1000);

                var showTime = that.secondToTime(that.time);
                $('lb_limit_time', node).setString(showTime);
                if (that.countFunc) {
                    that.unschedule(that.countFunc);
                    that.countFunc = null;
                }

                if (that.time <= 0) { //打开的一瞬间 时间到了
                    callBack();
                }
                that.countFunc = function () {
                    that.time--;
                    if (that.time <= 0) {
                        callBack();
                        that.unschedule(that.countFunc);
                    } else {
                        var showTime = that.secondToTime(that.time);
                        $('lb_limit_time', node).setString(showTime);
                    }
                };
                that.schedule(that.countFunc,1);
            }
        },
    });
    exports.TicketShopLayer = TicketShopLayer;

})(window);